package com.kexio.gen.config;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * JSON字符串序列化器
 * 
 * 将数据库中的JSON字符串字段自动转换为JSON对象返回给前端
 * 
 * @author 系统
 * @since 2025-09-16
 */
public class JsonStringSerializer extends JsonSerializer<String> {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null || value.trim().isEmpty()) {
            gen.writeNull();
            return;
        }

        try {
            // 尝试解析JSON字符串
            Object jsonObject = OBJECT_MAPPER.readValue(value, Object.class);
            // 直接写入JSON对象（不是字符串）
            gen.writeObject(jsonObject);
        } catch (JsonProcessingException e) {
            // 如果不是有效JSON，则作为普通字符串处理
            gen.writeString(value);
        }
    }
}

